<?php
namespace app\modules\index\controllers;

use app\common\controllers\CorsController;
use app\modules\index\services\ActivityService;
use app\modules\index\services\CalculateService;
use app\modules\index\services\DeliveryService;
use app\modules\index\services\MerchantService;
use app\modules\pay\services\PaymentService;
use yii\base\UserException;

class CalculateController extends CorsController{

    //计算活动价格
    public function actionCalc(){
        $merchant_id = \Yii::$app->getRequest()->post('merchant_id');
        $goods_item = \Yii::$app->getRequest()->post('goods_item');
        $source = \Yii::$app->getRequest()->post('source');
        $lng_lat = \Yii::$app->getRequest()->post('lng_lat');

        //计算商品价格
        $goods_data = CalculateService::calc($merchant_id,$goods_item);
        if(!$goods_data) {
            throw new UserException(CalculateService::getError());
        }
        //计算配送费
        $delivery_data = ['distance'=>0,'delivery_price'=>0];
        if(!empty($lng_lat)){
            $delivery_data = DeliveryService::calc($merchant_id,$lng_lat);
        }
        //计算活动最优惠价格
        $act_data = ActivityService::calc($goods_data['total_price'],$merchant_id);
        $total_price = $goods_data['total_price'] + $delivery_data['delivery_price'];

        return [
            'delivery_date_list'=>CalculateService::makeDeliveryDate(MerchantService::getInfoById($merchant_id)['business_time']),
            'goods_item'=>$goods_data['goods_item'],
            'delivery_info'=>$delivery_data,
            'activity_info'=>$act_data['act_info'],
            'store_info'=>MerchantService::getInfoById($merchant_id),
            'price_info'=>[
                'total_price'=>$total_price,
                'goods_total_price'=>$goods_data['total_price'],
                'delivery_price'=>$delivery_data['delivery_price'],
                'coupon_price'=>$act_data['coupon_price'],
                'real_price'=>round($total_price - $act_data['coupon_price'],2)
            ],
            'payment_list'=>PaymentService::supportList($source,$merchant_id),
        ];
    }
}